package com.atguigu.ssyx.activity.service.impl;

import com.atguigu.ssyx.activity.mapper.ActivityInfoMapper;
import com.atguigu.ssyx.activity.mapper.ActivityRuleMapper;
import com.atguigu.ssyx.activity.mapper.ActivitySkuMapper;
import com.atguigu.ssyx.activity.service.ActivityInfoService;
import com.atguigu.ssyx.client.product.ProductFeignClient;
import com.atguigu.ssyx.enums.ActivityType;
import com.atguigu.ssyx.model.activity.ActivityInfo;
import com.atguigu.ssyx.model.activity.ActivityRule;
import com.atguigu.ssyx.model.activity.ActivitySku;
import com.atguigu.ssyx.model.base.BaseEntity;
import com.atguigu.ssyx.model.product.SkuInfo;
import com.atguigu.ssyx.vo.activity.ActivityRuleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Windows
* @description 针对表【activity_info(活动表)】的数据库操作Service实现
* @createDate 2023-11-15 11:31:28
*/
@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo>
    implements ActivityInfoService{

    @Autowired
    private ActivityInfoMapper activityInfoMapper;

    @Autowired
    private ActivityRuleMapper activityRuleMapper;

    @Autowired
    private ActivitySkuMapper activitySkuMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    //优惠活动列表方法
    @Override
    public IPage<ActivityInfo> selectPage(Page<ActivityInfo> pageParam) {
        QueryWrapper<ActivityInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        IPage<ActivityInfo> page = activityInfoMapper.selectPage(pageParam, queryWrapper);
        page.getRecords().stream().forEach(item -> {
            item.setActivityTypeString(item.getActivityType().getComment());
        });
        return page;
    }


    @Override
    public Map<String, Object> findActivityRuleList(Long activityId) {
        HashMap<String, Object> result = new HashMap<>();

        List<ActivityRule> activityRuleList = activityRuleMapper.selectList( new LambdaQueryWrapper<ActivityRule>()
                .eq(ActivityRule::getActivityId, activityId));
        result.put("activityRuleList", activityRuleList);

        List<ActivitySku> activitySkuList = activitySkuMapper.selectList(new LambdaQueryWrapper<ActivitySku>()
                .eq(ActivitySku::getActivityId, activityId));
        List<Long> skuIdList = activitySkuList.stream().map(ActivitySku::getSkuId).collect(Collectors.toList());
        List<SkuInfo> skuInfoList = productFeignClient.findSkuInfoList(skuIdList);
        if (!CollectionUtils.isEmpty(skuIdList)){
            result.put("skuInfoList", skuInfoList);
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveActivityRule(ActivityRuleVo activityRuleVo) {
        // 先删除
        activityRuleMapper.delete(new LambdaQueryWrapper<ActivityRule>()
                .eq(ActivityRule::getActivityId, activityRuleVo.getActivityId()));

        activitySkuMapper.delete(new LambdaQueryWrapper<ActivitySku>()
                .eq(ActivitySku::getActivityId,activityRuleVo.getActivityId()));

        List<ActivityRule> activityRuleList = activityRuleVo.getActivityRuleList();
        List<ActivitySku> activitySkuList = activityRuleVo.getActivitySkuList();
        List<Long> couponIdList = activityRuleVo.getCouponIdList();

        // 增加
        ActivityInfo activityInfo = activityInfoMapper.selectById(activityRuleVo.getActivityId());
        for (ActivityRule activityRule : activityRuleList) {
            activityRule.setActivityId(activityRuleVo.getActivityId());
            activityRule.setActivityType(activityInfo.getActivityType());
            activityRuleMapper.insert(activityRule);
        }

        for (ActivitySku activitySku : activitySkuList) {
            activitySku.setActivityId(activityRuleVo.getActivityId());
            activitySkuMapper.insert(activitySku);
        }

    }

    @Override
    public List<SkuInfo> findSkuInfoByKeyword(String keyword) {
        List<SkuInfo> skuInfoList = productFeignClient.findSkuInfoByKeyword(keyword);

        // 如果没有查出直接返回空
        if (CollectionUtils.isEmpty(skuInfoList)) {
            return null;
        }
        List<Long> skuIdList = skuInfoList.stream().map(BaseEntity::getId).collect(Collectors.toList());

        // 已经存在的skuId，一个sku只能参加一个促销活动，存在的sku要进行排除
        List<Long> existSkuIdList = activityInfoMapper.selectExistSkuIdList(skuIdList);

        // 过滤掉查询出的已存在的值
        List<SkuInfo> notExistSkuInfoList = skuInfoList.stream().filter(skuInfo -> !existSkuIdList.contains(skuInfo.getId())).collect(Collectors.toList());

        return notExistSkuInfoList;
    }

    @Override
    public List<ActivityRule> findActivityRule(Long skuId) {

        List<ActivityRule> activityRuleList = activityInfoMapper.selectActivityRuleList(skuId);
        if (!CollectionUtils.isEmpty(activityRuleList)) {
            activityRuleList.forEach(activityRule -> activityRule.setRuleDesc(this.getRuleDesc(activityRule)));
        }

        return activityRuleList;
    }

    @Override
    public Map<Long, List<String>> findActivity(List<Long> skuIdList) {

        Map<Long, List<String>> result = new HashMap<>();
        skuIdList.forEach(skuId -> {
            // 根据skuId进行查询，查询sku对应活动规则列表
            List<ActivityRule> activityRuleList = this.findActivityRule(skuId);

            if (!CollectionUtils.isEmpty(activityRuleList)) {
                List<String> ruleList = new ArrayList<>();
                activityRuleList.forEach(activityRule -> ruleList.add(this.getRuleDesc(activityRule)));
                result.put(skuId, ruleList);
            }
        });
        return result;
    }

    private String getRuleDesc(ActivityRule activityRule) {
        ActivityType activityType = activityRule.getActivityType();
        StringBuffer ruleDesc = new StringBuffer();

        if (activityType == ActivityType.FULL_REDUCTION) {
            ruleDesc
                    .append("满")
                    .append(activityRule.getConditionAmount())
                    .append("元减")
                    .append(activityRule.getBenefitAmount())
                    .append("元");
        } else {
            ruleDesc
                    .append("满")
                    .append(activityRule.getConditionAmount())
                    .append("元打")
                    .append(activityRule.getBenefitAmount())
                    .append("折");
        }
        return ruleDesc.toString();
    }
}




